//
//  CSJStatusViewModel.swift
//  weibo
//
//  Created by 崔顺建 on 16/8/12.
//  Copyright © 2016年 cui. All rights reserved.
//

import UIKit

class CSJStatusViewModel: NSObject {
    
    lazy var statusList: [CSJStatusModel] = [CSJStatusModel]()
    
    
    func loadData(isPullUp: Bool ,callBack:(isSuccess: Bool, message: String) -> ()) {
        var maxId: Int64 = 0
        
        var sinceId: Int64 = 0
        
        if isPullUp {
        
        maxId = self.statusList.last?.status?.id ?? 0
            if maxId > 0 {
            
                maxId -= 1
            
            }
        }else {
        sinceId = self.statusList.first?.status?.id ?? 0
        
        }
        
        var result = "没有加载到最新微博数据"
        
        CSJNetTools.sharedTools.requestNewStatus(CSJUserAccountViewModel.shardUserAccount.accessToken!,maxId: maxId, sinceId: sinceId) { (response, error) -> () in

            if error != nil {
                print("加载失败")
                callBack(isSuccess: false ,message: result)
                return
            }
            
            guard let dic = response as? [String :AnyObject] else {
                callBack(isSuccess: false ,message: result)
                return
            }
            // 字典格式正确
            guard let dicArray = dic["statuses"] as? [[String :AnyObject]] else {
                callBack(isSuccess: false,message: result)
                return
            }
            var tempArray = [CSJStatusModel]()
            
            for value in dicArray {
                
                let status = StatusModel(dic: value)
                let statusViewmodel = CSJStatusModel(status: status)
                
                tempArray.append(statusViewmodel)
            }
            if isPullUp {
                self.statusList.appendContentsOf(tempArray)
            
            }else {
            
            self.statusList.insertContentsOf(tempArray, at: 0)
             
            }
            
            if tempArray.count > 0 {
            
            result = "加载了\(tempArray.count)条数据"
            
            }
            
            callBack(isSuccess: true ,message: result)
        }
        
       
    }


}
